<template>
  <view class="indexPage">
    <s-nav-bar title="档期管理" :background="'transparent'" :titleStyle="{ color: '000', fontWeight: 'bold' }" statusBar back
      :backStyle="{ color: '000' }"></s-nav-bar>

    <!-- 顶部背景 -->
    <view class="top-bg"></view>

    <!-- 日历组件 -->
    <view class="calendar-container">
      <v-calendar :marksData="calendarMarks" :selectDate="currentDate" @day-selected="handleDaySelected"></v-calendar>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="main-scroll" scroll-y>
      <view class="top_info">
        <view class="day">{{ displayDate }},{{ selectedOrders.length }}条订单</view>
        <view class="link" @click="addNew">
          <s-icon name="add" size="14"></s-icon>
          <view class="text">新增订单</view>
        </view>
      </view>
      <view v-if="selectedOrders.length > 0" class="order-list">
        <view v-for="(order, index) in selectedOrders" :key="index" class="order-card"
          :class="order.status == '已完成' ? 'disabled' : ''">
          <!-- 顶部信息 -->
          <view class="card-header">
            <text class="order-no">编号：{{ order.order_number }}</text>
            <text class="order-channel">渠道：{{ order.channel }}</text>
          </view>

          <!-- 主体信息 -->
          <view class="card-body">
            <!-- 第一行：标题 -->
            <view class="info-line title">
              {{ order.customer_name }} - {{ order.type }}
            </view>

            <!-- 第二行：联系方式 -->
            <view class="info-line row">
              <view class="left">电话：{{ order.phone }}</view>
            </view>
            <!-- 第三行：日期信息 -->
            <view class="meta-line">
              <!-- 左侧日期信息 -->
              <view class="date-info">
                <view class="info-line">开始：{{ formatDate(order.start_date) }}</view>
                <view class="info-line">结束：{{ formatDate(order.end_date) }}</view>
              </view>

              <!-- 右侧档期信息 -->
              <view class="due-info">
                <view class="due-number">
                  <view class="number" v-if="getScheduleDays(order) > 0">
                    {{ getScheduleDays(order) }}
                  </view>
                  <view class="text">
                    天档期
                  </view>
                </view>
              </view>
            </view>

            <!-- 金额区块 -->
            <view class="amount-box">
              <view class="amount-item">
                <text class="amount-label">总金额</text>
                <text class="amount-value" style="color:var(--v-green)">{{ order.total_amount }}元</text>
              </view>
              <view class="amount-item">
                <text class="amount-label">已付金额</text>
                <text class="amount-value">{{ order.deposit }}元</text>
              </view>
              <view class="amount-item">
                <text class="amount-label">尾款</text>
                <text class="amount-value" style="color:var(--v-danger)">{{ order.final_payment }}元</text>
              </view>
            </view>
          </view>
          <!-- 底部操作 -->
          <view class="card-footer">
            <view class="action-buttons">
              <button class="edit-btn" @click="editOrder(order)">
                编辑订单
              </button>
              <button class="complete-btn" @click="completeOrder(order)" v-if="order.status != '已完成'">
                项目完成
              </button>
              <button class="complete-btn disabled" v-else>已完成</button>
            </view>
          </view>
          <view class="finished" v-if="order.status == '已完成'">
            <image style="width:100%;" mode="widthFix"
              src="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/finish.png"></image>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <s-empty v-else src="https://img01.yzcdn.cn/vant/empty-image-default.png"
        :text="currentDate ? '该日期无订单数据' : '请选择日期查看订单'"></s-empty>

      <view class="view-all">
        <button class="edit-btn" @click="viewAll">查看全部订单</button>
      </view>
      <!-- 加载错误提示 -->
      <view class="error-tips" v-if="error && !loading">
        <text>加载失败，请</text>
        <text class="retry" @click="retryLoad">点击重试</text>
      </view>

      <!-- 加载中提示 -->
      <view class="loading-more" v-if="loading">
        <s-icon name="loading" size="24" color="#999"></s-icon>
        <text>加载中...</text>
      </view>

      <!-- 没有更多提示 -->
      <view class="no-more" v-if="finished && selectedOrders.length > 0">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部导航 -->
    <v-tabbar :version="version" @tabBarChange="tabBarChange" :tabIndex="3" />
  </view>
</template>

<script>
import sIcon from '@/uni_modules/s-ui/components/s-icon/s-icon.vue'
import sEmpty from '@/uni_modules/s-ui/components/s-empty/s-empty.vue'

export default {
  components: {
    sIcon,
    sEmpty
  },
  data() {
    return {
      version: "",
      calendarMarks: {},
      selectedOrders: [],
      allOrders: [],
      loading: false,
      finished: false,
      refreshing: false,
      error: false,
      page: 1,
      pageSize: 10,
      currentDate: null,
      today: null,
    };
  },
  computed: {
    displayDate() {
      if (!this.currentDate) {
        return `${this.today.year}年${this.today.month}月${this.today.day}日`;
      }
      const [year, month, day] = this.currentDate.split('-');
      return `${year}年${month}月${day}日`;
    }
  },
  onShow() {
    this.version = uni.getStorageSync('version')
    this.sjuLogin.checkLogin();
    const today = new Date();
    this.today = {
      year: today.getFullYear(),
      month: today.getMonth() + 1,
      day: today.getDate(),
    };

    const savedDate = null;
    // const savedDate = this.getSavedDate();

    this.loadAllOrders().then(() => {
      if (savedDate) {
        const [year, month, day] = savedDate.split('-');
        this.currentDate = savedDate;
        const dateObj = {
          year: parseInt(year),
          month: parseInt(month),
          day: parseInt(day),
          marks: this.calendarMarks[savedDate] || []
        };
        this.handleDaySelected(dateObj);
      } else {
        this.currentDate = `${this.today.year}-${this.today.month}-${this.today.day}`;
        this.handleDaySelected({
          year: this.today.year,
          month: this.today.month,
          day: this.today.day,
          marks: this.calendarMarks[
            `${this.today.year}-${this.today.month}-${this.today.day}`
          ] || [],
        });
      }
    });
  },
  methods: {
    saveSelectedDate(dateStr) {
      uni.setStorageSync('selectedDate', dateStr);
    },

    getSavedDate() {
      return uni.getStorageSync('selectedDate');
    },

    addNew() {
      uni.navigateTo({
        url: "/pages/order/index"
      });
    },

    viewAll() {
      this.sjuNav.navigateTo("pages/order/list");
    },
    async loadAllOrders() {
      this.loading = true;
      this.error = false;

      try {
        const res = await this.sjuAjax.get("/order/list", {
          page: 1,
          pageSize: 1000,
          has_material: "" // 添加这个参数获取所有订单
        });

        if (res.code === 200) {
          this.allOrders = res.data.list || [];
          console.log('加载到的订单数据:', this.allOrders); // 添加调试日志
          this.generateCalendarMarks();
        } else {
          this.error = true;
          uni.showToast({
            title: res.msg || "加载订单失败",
            icon: "none",
          });
        }
      } catch (err) {
        this.error = true;
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    generateCalendarMarks() {
      const marks = {};
      console.log('开始生成日历标记，订单数量:', this.allOrders.length);

      this.allOrders.forEach((order) => {
        if (!order.start_date || !order.end_date) {
          console.warn('订单缺少日期信息:', order);
          return;
        }

        try {
          const startDate = new Date(order.start_date);
          const endDate = new Date(order.end_date);

          // 确保日期有效
          if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
            console.warn('订单日期格式无效:', order);
            return;
          }

          for (
            let d = new Date(startDate);
            d <= endDate;
            d.setDate(d.getDate() + 1)
          ) {
            const dateStr = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
            console.log('添加订单标记:', dateStr, order.order_number);

            if (!marks[dateStr]) {
              marks[dateStr] = [];
            }

            marks[dateStr].push({
              type: "order",
              title: `订单 ${order.order_number}`,
              color: this.getOrderColor(order),
              detail: order,
            });
          }
        } catch (e) {
          console.error('处理订单日期时出错:', e, order);
        }
      });

      this.calendarMarks = marks;
      console.log('生成的日历标记:', this.calendarMarks);
    },

    getOrderColor(order) {
      const statusColors = {
        待处理: "var(--v-theme)",
        进行中: "#4ECDC4",
        已完成: "#A5A5A5",
        已取消: "#FF6B6B",
      };
      return statusColors[order.status] || "var(--v-theme)";
    },

    formatDate(dateStr) {
      if (!dateStr) return "";
      return dateStr.split(" ")[0];
    },

    // 计算档期天数（结束日期-开始日期）
    getScheduleDays(order) {
      if (!order.start_date || !order.end_date) return 0;
      const startDate = new Date(order.start_date);
      const endDate = new Date(order.end_date);
      const diffTime = endDate - startDate;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // +1 因为包括开始日期当天
      return diffDays;
    },

    getDueColor(order) {
      const dueDays = this.getDueDays(order);
      if (dueDays < 0) return "#FF6B6B";
      if (dueDays <= 3) return "#FFBE0B";
      return "#4ECDC4";
    },

    getDueDays(order) {
      if (!order.end_date || !this.currentDate) return 1000;

      const endDate = new Date(order.end_date);
      const [year, month, day] = this.currentDate.split("-");
      const selectedDate = new Date(year, month - 1, day);

      const diffTime = endDate - selectedDate;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays;
    },

    handleDaySelected({ year, month, day, marks }) {
      const dateStr = `${year}-${month}-${day}`;
      this.currentDate = dateStr;

      this.saveSelectedDate(dateStr);

      // 确保marks存在且是数组
      const validMarks = marks || [];
      this.selectedOrders = validMarks
        .filter((mark) => mark && mark.type === "order")
        .map((mark) => mark.detail);

      console.log('选中的订单:', this.selectedOrders); // 添加调试日志
      this.page = 1;
      this.finished = false;

      // this.$nextTick(() => {
      //   const calendar = this.$refs.calendar;
      //   if (calendar) {
      //     calendar.setSelectedDate(`${year}-${month}-${day}`);
      //   }
      // });
    },

    async loadOrders() {
      if (this.loading || this.finished || !this.currentDate) return;

      this.loading = true;
      this.error = false;

      try {
        const res = await this.sjuAjax.get("/order/list", {
          page: this.page,
          pageSize: this.pageSize,
          date: this.currentDate,
        });

        this.loading = false;
        this.refreshing = false;

        if (res.code === 200) {
          const data = res.data || {};
          const list = data.list || [];

          if (this.page === 1) {
            this.selectedOrders = list;
          } else {
            this.selectedOrders = [...this.selectedOrders, ...list];
          }

          if (
            list.length < this.pageSize ||
            this.page >= data.pagination.totalPages
          ) {
            this.finished = true;
          } else {
            this.page++;
          }
        } else {
          this.error = true;
          uni.showToast({
            title: res.msg || "加载失败",
            icon: "none",
          });
        }
      } catch (err) {
        this.loading = false;
        this.refreshing = false;
        this.error = true;
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },

    retryLoad() {
      this.error = false;
      this.loadOrders();
    },

    handleRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.finished = false;
      this.loadOrders();
    },

    editOrder(order) {
      uni.navigateTo({
        url: `/pages/order/edit?id=${order.id}`,
      });
    },

    handleMaterial(order) {
      uni.navigateTo({
        url: `/pages/material/upload?id=${order.id}`,
      });
    },

    async completeOrder(order) {
      uni.showModal({
        title: "确认操作",
        content: `确定要将订单 ${order.order_number} 标记为已完成吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const completeRes = await this.sjuAjax.post("/order/complete", {
                id: order.id,
              });

              if (completeRes.code === 200) {
                uni.showToast({ title: "操作成功", icon: "success" });
                order.status = "已完成";
                this.generateCalendarMarks();
                this.handleDaySelected({
                  year: parseInt(this.currentDate.split("-")[0]),
                  month: parseInt(this.currentDate.split("-")[1]),
                  day: parseInt(this.currentDate.split("-")[2]),
                  marks: this.calendarMarks[this.currentDate] || [],
                });
              } else {
                uni.showToast({
                  title: completeRes.msg || "操作失败",
                  icon: "none",
                });
              }
            } catch (err) {
              uni.showToast({ title: "网络错误，请重试", icon: "none" });
            }
          }
        },
      });
    },

    tabBarChange(url) {
      uni.switchTab({
        url: url,
      });
    },
  },
};
</script>

<style lang="less">
.indexPage {
  background-color: var(--v-bg);
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top_info {
  margin: 30rpx 20rpx;
  margin-top: 0;
  background: var(--v-white);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 34rpx;
  border-radius: 10rpx;
  box-shadow: var(--v-shadow);

  .link {
    display: flex;
    align-items: center;
    color: var(--v-theme);
    ;

    .text {
      margin-left: 10rpx;
    }
  }
}

.top-bg {
  width: 100%;
  height: 312rpx;
  border-radius: 0 0 24rpx 24rpx;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
}

.calendar-container {
  background: var(--v-white);
  border-radius: 16rpx;
  margin: 20rpx;
  box-shadow: var(--v-shadow);
  z-index: 1;
}

.main-scroll {
  flex-grow: 1;
  height: 0;
  box-sizing: border-box;
}

.order-list {
  display: flex;
  flex-direction: column;
  padding: 0 20rpx 20rpx;

  .order-card {
    position: relative;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    &.disabled {
      background: #dddee8;

      .amount-item {
        background: #e8e9f4;
      }

      .edit-btn {
        opacity: .6;
      }

      .card-header,
      .card-footer {
        border-color: #c9c9c9;
      }
    }

    .finished {
      width: 124rpx;
      height: 124rpx;
      position: absolute;
      right: 30rpx;
      top: 100rpx;
      pointer-events: none;

      .text {
        font-size: 46rpx;
        color: rgba(0, 0, 0, .3);
        border-radius: 12rpx;
        border: rgba(0, 0, 0, .3) 6rpx solid;
        width: 180rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translateX(-50%) translateY(-50%) rotate(25deg);
      }
    }
  }
}

.order-card {
  background-color: var(--v-white);
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: var(--v-shadow);
}

.card-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid var(--v-bg);
  font-size: 26rpx;
  color: var(--v-gray);
}

.order-no {
  font-weight: bold;
}

.order-channel {
  color: #FF7A1C;
  ;
}

.card-body {
  padding: 20rpx;
  padding-bottom: 0;
}

.info-line {
  font-size: 26rpx;
  color: var(--v-gray);
  margin-bottom: 16rpx;
  line-height: 1.5;

  &.row {
    display: flex;
    justify-content: space-between;
  }
}

.info-line.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.meta-line {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  min-height: 80rpx;
}

.date-info {
  flex: 1;
}

.due-info {
  display: flex;
  align-items: baseline;
  margin-left: 20rpx;
}

.due-number {
  font-size: 28rpx;
  line-height: 1;
  color: var(--v-gray);
  display: flex;
  align-items: baseline;

  .number {
    margin-right: 10rpx;
    font-size: 68rpx;
    color: var(--v-green);

    &.orange {
      color: #ffbe0b;
    }

    &.red {
      color: #ff6b6b;
    }
  }
}

.amount-box {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 0;

  .amount-item {
    margin-right: 10rpx;

    &:last-child {
      margin-right: 0;
    }
  }
}

.amount-item {
  flex: 1;
  text-align: center;
  padding: 16rpx;
  background-color: var(--v-bg);
  border-radius: 8rpx;
}

.amount-label {
  display: block;
  font-size: 26rpx;
  color: var(--v-gray);
  margin-bottom: 8rpx;
}

.amount-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--v-theme);
}

.card-footer {
  padding: 20rpx;
  border-top: 1rpx solid var(--v-bg);
}

.action-buttons {
  display: flex;
  justify-content: space-between;

  .edit-btn,
  .complete-btn {
    margin-right: 10rpx;

    &:last-child {
      margin-right: 0;
    }
  }
}

.edit-btn,
.complete-btn {
  height: 68rpx;
  line-height: 68rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  flex: 1;
}

.edit-btn {
  width: 292rpx;
  height: 68rpx;
  background-color: var(--v-white);
  color: #FF7A1C;
  border: 1rpx solid #FF7A1C;
}

.complete-btn {
  width: 292rpx;
  height: 68rpx;
  color: white;
  background: #FF7A1C;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
}

.loading-more,
.no-more,
.error-tips {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
}

.loading-more {
  s-icon {
    margin-right: 10rpx;
    animation: rotate 1s linear infinite;
  }
}

.error-tips {
  color: #ff6b6b;

  .retry {
    color: var(--v-theme);
    margin-left: 10rpx;
    text-decoration: underline;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.view-all {
  padding: 10rpx 30rpx 60rpx 30rpx;
}
</style>